<template>
  <div class="tree">
    <div
      class="parent"
      v-for="(data, index) of treeData"
      :key="data.id">
      <div class="node">
        <span @click="data.expand=!data.expand" v-if="data.children && data.children.length" class="expandIcon">
          <i class="ivu-icon ivu-icon-ios-arrow-down" v-if="data.expand"></i>
          <i class="ivu-icon ivu-icon-ios-arrow-forward" v-else></i>
        </span>
        <!-- 传入改变权限了的id -->
        <Checkbox v-model="data.isChecked" @on-change="dataChange(data.isChecked, index, data.id)">{{data.name}}</Checkbox>
      </div>
      <div
        class="children"
        v-if="data.children && data.children.length"
        v-show="data.expand">
        <!-- vue可以通过name选项的设置递归调用自己 -->
        <tree
          @refesh="refesh"
          :treeData="data.children">
        </tree>
      </div>
    </div>
  </div>
</template>
 
<script>
export default {
  name: 'tree',
  props: {
    treeData: {
      type: Array
    }
  },
  methods: {
    refesh(){
      this.$emit('refesh')
    },
    // isChecked表示当前权限是否被选中
    // index表示当前treeData中的第几个权限
    // id是改编权限的id
    dataChange(isChecked, index, id) {
      //如果选择当前权限，则他所有的子权限都需要选择,并且展开
      if(this.treeData[index].children){
        this.treeData[index].expand = true
        this.dfs(isChecked, this.treeData[index].children)
      }
      this.refesh()
    },
    dfs(isChecked, data){
      for(let i = 0; i < data.length; i++){
        data[i].expand = true
        data[i].isChecked = isChecked
        if(data[i].children){
          this.dfs(isChecked, data[i].children)
        }
      }
    }
  }
}
</script>
 
<style scoped>

</style>